'use strict';
var cmsDirectives = angular.module('cmsDirectives');

cmsDirectives.directive('themeSelection', ['$rootScope', 'Constant', 'AppOpt', 'cmsService', 'ThemeOpt',
    function ($rootScope, Constant, AppOpt, cmsService, ThemeOpt) {
        return {
            restrict: 'E',
            replace: true,
            //transclude: true,
            scope: {
                themeItems: '=ngModel'
            },
            link: function (scope, element, attrs) {
                scope.$watch('themeItems', function (newVal, oldVal) {
                    if (newVal) {
                        var items = newVal;
                        var ul = angular.element('<ul></ul>');
                        element.append(ul);
                        ul.jcarousel();

                        angular.forEach(items, function(item, i) {
                            var cls = item.code === $rootScope.CurrentApp.theme ? 'active' : '';

                            ul.jcarousel('add', i + 1, [
                                '<li id="jcarousel-item--' + item.code + '--' + i + '" class="theme-item ' + cls + '">',
                                '<div class="jcarousel-item-inner">',
                                '<div><img src="' + item.image + '" ></div>',
                                '<div class="text">' + item.name + '</div>',
                                '</div>',
                                '</li>'
                            ].join(''));
                        });
                        ul.jcarousel({
                            size: items.length,
                            scroll: 3,
                            visible: 3
                            //wrap: 'circular',
                            //itemFallbackDimension: 540
                        });

                        $(".jcarousel-container").delegate('li.theme-item','click',function(e) {
                                var themeCode = $(this).attr('id').split('--')[1];
                                if (themeCode != 'flat') {
                                    alertify.alert('<span class="my-error">Will support more themes soon!</span>');
                                    return; // TODO:
                                }

                                $('li.jcarousel-item').removeClass('active');
                                $(this).addClass('active');

                                var json = AppOpt.opt({action: 'updateTheme', appId: $rootScope.CurrentAppId, theme: themeCode},function() {
                                    //console.log(json);
                                    $rootScope.CurrentApp.theme = themeCode;
                                });
                        });
                    }
                });
            }
        }
    }]);

